<template>
  <a-form
    ref="loginForm"
    :model="userInfo"
    class="login-form"
    layout="vertical"
    @submit="handleSubmit"
  >
    <a-form-item
      field="username"
      :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input
        v-model="userInfo.username"
        :placeholder="$t('login.form.userName.placeholder')"
      >
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      field="password"
      :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input-password
        v-model="userInfo.password"
        :placeholder="$t('login.form.password.placeholder')"
        allow-clear
      >
        <template #prefix>
          <icon-lock />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item
      field="username"
      :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input v-model="userInfo.captcha" placeholder="请输入验证码">
        <template #prefix>
          <icon-image />
        </template>
      </a-input>
      <img :src="captchaBase64Img" @click="getCaptchaImage" />
    </a-form-item>
    <a-space :size="16" direction="vertical">
      <div class="login-form-password-actions">
        <a-checkbox
          checked="rememberPassword"
          :model-value="loginConfig.rememberPassword"
          @change="setRememberPassword as any"
        >
          {{ $t('login.form.rememberPassword') }}
        </a-checkbox>
        <a-link>{{ $t('login.form.forgetPassword') }}</a-link>
      </div>
      <a-button type="primary" html-type="submit" long :loading="loading">
        {{ $t('login.form.login') }}
      </a-button>
      <a-button type="text" long class="login-form-register-btn">
        {{ $t('login.form.register') }}
      </a-button>
    </a-space>
  </a-form>
</template>

<script setup lang="ts">
  import useLoading from '@/hooks/loading';
  import { useUserStore } from '@/store';
  import { useStorage } from '@vueuse/core';
  import { onMounted, reactive, ref, defineEmits } from 'vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import type { LoginData } from '@/api/user';
  import { useI18n } from 'vue-i18n';
  import { randomImage } from '@/api/user';
  import { v4 as uuidv4 } from 'uuid';

  const { t } = useI18n();
  const emits = defineEmits(['loginSuccess']);
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const errorMessage = ref('');
  const loginConfig = useStorage('login-config-password', {
    rememberPassword: false,
    username: 'jeecg',
    password: 'jeecg1314',
    captcha: 'ZfwA',
    checkKey: '',
  });
  const captchaBase64Img = ref('');
  const userInfo = reactive({
    // username: loginConfig.value.username,
    // password: loginConfig.value.password,
    username: 'admin',
    password: 'jeecg1314',
    captcha: 'ZfwA',
    checkKey: '',
  });

  const getCaptchaImage = async () => {
    const key = uuidv4();
    const res = await randomImage(key);
    userInfo.checkKey = key;
    captchaBase64Img.value = res.data;
  };

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login(values as LoginData);

        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
        emits('loginSuccess');
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };

  onMounted(() => {
    getCaptchaImage();
  });
</script>

<style scoped lang="less"></style>
